<template>
  <van-nav-bar title="登录"></van-nav-bar>
  <van-form @submit="onSubmit">
    <van-cell-group inset>
      <van-field v-model="UserForm.username" name="username" label="用户名" placeholder="用户名" :rules="[{ required: true, message: '请填写用户名' }, {
        pattern: /^\w{6,16}$/, message: '用户名格式不正确'
      }]" />
      <van-field v-model="UserForm.password" type="password" name="password" label="密码" placeholder="密码" :rules="[{ required: true, message: '请填写密码' }, {
                pattern: /^\w{6,16}$/, message: '用户名格式不正确'
      }]" />
    </van-cell-group>
    <div style="margin: 16px;">
      <van-button round block type="primary" native-type="submit">
        登录
      </van-button>
    </div>
    <van-row justify="end">
      <router-link class="link" to="/register">注册账号</router-link>
    </van-row>

  </van-form>

</template>
<script lang="ts" setup>
import type { LoginUser } from '@/types/data'
import { reactive } from 'vue'
import { login } from '@/api/user'
import { showNotify } from 'vant'
import 'vant/es/notify/style';
import { useRouter } from 'vue-router'
import type { AxiosError } from 'axios'
//登录时存储token
import useTokenStore from '@/stores/token'
const { updateToken } = useTokenStore()

const router = useRouter()
defineOptions({
  name: 'RegisterPage'
})
const UserForm = reactive<LoginUser>({
  username: '',
  password: ''
})

const onSubmit = async (values: LoginUser) => {
  try {
    const res = await login(values)
    console.log('我是你的Token',res.data.token)
    updateToken(res.data.token) // 设置token
    showNotify({ type: 'success', message: '注册成功' })
    router.push("/")
  } catch (error) {
    const e = error as AxiosError
    showNotify({ type: "danger", message: e.message })
  }

}

</script>
<style scoped>
.link {
  color: #069;
  font-size: 12px;
  padding-right: 20px;
}
</style>